package com.wan.servlet.provider;

import com.alibaba.fastjson.JSONArray;
import com.wan.pojo.Provider;
import com.wan.pojo.Role;
import com.wan.pojo.User;
import com.wan.service.Provider.ProviderServiceImpl;
import com.wan.service.role.RoleServiceImpl;
import com.wan.service.user.UserServiceImpl;
import com.wan.util.Constants;
import com.wan.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")) {
            this.query(req,resp);
        }else if (method.equals("add")) {
            this.addProvider(req,resp);
        }else if (method.equals("delprovider")) {
            this.deleteProviderById(req,resp);
        }else if (method.equals("modify")) {
            this.dispatcherModifyPage(req,resp);
        }else if (method.equals("modifyexe")) {
            this.modifyProvider(req,resp);
        }else if (method.equals("view")) {
            this.viewProvider(req,resp);
        }


    }
    // 跳转到查看页面，要携带这个用户
    public void viewProvider (HttpServletRequest req, HttpServletResponse resp) {
        // 从请求获取参数
        String id = req.getParameter("proid");

        Provider provider = null;
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        if (id != null) {
            provider = providerService.getProviderById(Integer.valueOf(id));
        }
        // 携带参数
        req.setAttribute("provider",provider);
        // 跳转查看页面
        try {
            req.getRequestDispatcher("/jsp/providerview.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 处理修改之后的信息提交
    public void modifyProvider (HttpServletRequest req, HttpServletResponse resp) {
        // 从前端的隐藏域获取到这个用户
        String id = req.getParameter("proId");
        // 从前端获取可填写的信息
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        Provider provider = providerService.getProviderById(Integer.valueOf(id));
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setModifyDate(new Date(System.currentTimeMillis()));

        User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);

        int impactCount = providerService.updateProvider(provider,user.getId());

        if (impactCount > 0) {
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                req.getRequestDispatcher("providermodify.jsp").forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 跳转到修改用户的界面，在这个过程中需要携带这个用户的信息，用以前端直接获取
    public void dispatcherModifyPage (HttpServletRequest req, HttpServletResponse resp) {
        // 跳转的时候携带的id，通过这个id查找到这个用户
        String id = req.getParameter("proid");

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        Provider provider = providerService.getProviderById(Integer.valueOf(id));

        if (provider != null) {
            req.setAttribute("provider",provider);
            try {
                req.getRequestDispatcher("/jsp/providermodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 通过一个供应商删除 ,这里js中使用了ajax
    public void deleteProviderById (HttpServletRequest req, HttpServletResponse resp) {
        // ajax，传递过来的参数，表示当前供应商的id
        String id = req.getParameter("proid");

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        int impactCount = providerService.deleteProvider(Integer.valueOf(id));

        // 用map把返回信息存储起来，方便后续转换成json的格式
        Map<String, String> resultMap = new HashMap<String,String>();

        if (id == null){
            resultMap.put("delResult","notexist");
        } else {
            // 如果受影响的行数大于0，那么表示删除成功
            if (impactCount > 0) {
                resultMap.put("delResult","true");
            }else if (impactCount == 0) {
                resultMap.put("delResult","false");
            }
        }
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 添加一个供应商
    public void addProvider (HttpServletRequest req, HttpServletResponse resp) {
        // 从前端获取表单填写的数据
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        // 创建一个供应商实体
        Provider provider = new Provider();

        // 将获取的信息封装到实体
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setCreationDate(new Date(System.currentTimeMillis()));

        // 创建业务层对象
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int impactCount = providerService.addProvider(provider,user.getId());

        if (impactCount > 0) {
            try {
                resp.sendRedirect("/jsp/provider.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("/jsp/provideradd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    // 进入供应商界面，查询所有的供应商信息
    public void  query (HttpServletRequest req, HttpServletResponse resp) {
        // 从前端获取数据
        String queryProCode = req.getParameter("queryProCode");
        String queryProName = req.getParameter("queryProName");
        String pageIndex = req.getParameter("pageIndex");

        // 获取用户列表
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList = null;

        // 第一次走这个请求，一定是第一页，页面大小是固定的
        // 这个大小可以写到配置文件中，那样更容易更改，在这写的固定了就不好改
        int pageSize = 5;
        int currentPageNum = 1;

        if (queryProCode == "") {
            queryProCode = null;
        }
        if (queryProName == "") {
            queryProName = null;
        }
        if (pageIndex != null) {
            currentPageNum = Integer.parseInt(pageIndex);//解析出来的值就是1，这是默认情况下的东西
        }

        // 获取用户的总数(分页，上一页，下一页，首页，尾页)
        int totalCount = providerService.proCount(queryProCode, queryProName);
        PageSupport pageSupport = new PageSupport(); // 总页数支持
        pageSupport.setCurrentPageNo(currentPageNum);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 如果页面要小于1，就显示第一页
        if (totalPageCount < 1) {
            currentPageNum = 1;
        }else if (currentPageNum > totalPageCount) {
            currentPageNum = totalPageCount;
        }

        // 获取供应商列表展示 中间的一大堆都是为了执行这个代码，获得用户列表
        // 为了sql的正常运行，不能让任何一个数据的问题使得sql不能运行
        providerList = providerService.getProviderList(queryProCode,queryProName,currentPageNum,pageSize);
        // 将拿到的供应商列表
        req.setAttribute("providerList",providerList);

        // 返回页数，分页的相关支持
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNum);
        req.setAttribute("queryProName",queryProName);
        req.setAttribute("queryProCode",queryProCode);

        // 携带参数，返回前端看看
        try {
            req.getRequestDispatcher("/jsp/providerlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
